package com.beans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.event.SelectEvent;
import org.primefaces.model.DualListModel;
import org.springframework.context.annotation.Scope;

import com.controllers.RoleController;
import com.model.Action;
import com.model.Role;

@Named
@Scope(value = "request")
public class RoleBean implements Serializable {

	private static final long serialVersionUID = 244219072819116038L;

	private RoleController roleController;

	private Role role;

	private DualListModel<Action> actions;

	private List<Action> allActions;

	private List<Action> selectedActions;

	private List<Role> allRoles;

	@Inject
	public RoleBean(RoleController roleController) {
		this.roleController = roleController;
		allActions = roleController.getActions();
		selectedActions = new ArrayList<Action>();
		actions = new DualListModel<Action>(allActions, selectedActions);
		role = new Role();
		allRoles = roleController.getRoles();
	}

	public void save(ActionEvent actionEvent) {
		role.getActions().clear();
		role.getActions().addAll(actions.getTarget());
		roleController.saveRole(role);
		FacesContext.getCurrentInstance().addMessage(
				null,
				new FacesMessage("El Rol "
						+ role.getName() +" ha sido actualizado exitosamente"));
	}

	public void refreshActions(SelectEvent event) {

		role = (Role) event.getObject();
		List<Action> roleActions = roleController
				.getActionsByRole(role.getId());
		intersectActions(roleActions);
		actions = new DualListModel<Action>(allActions, roleActions);
		FacesContext.getCurrentInstance().addMessage(
				null,
				new FacesMessage("Editando Role :"
						+ " " + role.getName()));
	}

	private void intersectActions(List<Action> roleActions) {
		for (Action selected : roleActions)
			for (Action action : allActions) {
				{
					if (action.getId() == selected.getId()) {
						allActions.remove(action);
						break;
					}
				}
			}
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public DualListModel<Action> getActions() {
		return actions;
	}

	public void setActions(DualListModel<Action> actions) {
		this.actions = actions;
	}

	public List<Role> getAllRoles() {
		return allRoles;
	}

	public void setAllRoles(List<Role> allRoles) {
		this.allRoles = allRoles;
	}
}
